# -*- codeing -*-
# @Time : 2021/11/15 0:14
# @Author : Torres-圣君
# @File : __init__.py
# @Sofaware : PyCharm
from nonebot.plugin import on_regex
from nonebot.adapters.cqhttp import Bot, Event
from nonebot.adapters.cqhttp.message import Message
import requests
import json
import os

# 发送'lolxxx背景故事'，例：lol亚索背景故事
test = on_regex(r".*(lol).*(背景故事).*", priority=49)

pwd = os.path.split(os.path.realpath(__file__))[0]


@test.handle()
async def _(bot: Bot, event: Event):
    msg = str(event.get_message()).strip("lol背景故事 ")
    readly = False
    try:
        with open(pwd + r"/data/heroesID.json", "r", encoding='utf-8') as r:
            json_data = json.load(r)
            role_data = json_data.get("role")
            try:
                the_data = role_data[msg]
                hero_fullname = the_data["fullname"]
                hero_url = the_data["url"]
                # 根据链接获取对应英文名并且大写
                hero_name_en = hero_url.split('/')[-2]
            except:
                pass
            # 获取英雄对应的英文名
        readly = True
        photo = f'[CQ:image,file=https://game.gtimg.cn/images/lol/universe/v1/assets/images/champion/splash/{hero_name_en.title()}_0.jpg]'
        await test.send(message=Message(photo))


    except:
        readly = False
        pass

    if readly:
        await test.finish(message=Message((run(hero_name_en) +
                                           "\n————————————\n" +
                                           msg + "更多内容请点击：\n" +
                                           hero_url)))
    else:
        await test.finish(message=Message("您输入的英雄名字有误，或不存在."), at_sender=True)


# 获取英雄背景故事
def run(hero_name_en):
    url = f"https://yz.lol.qq.com/v1/zh_cn/champions/{hero_name_en}/index.json"
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36 Edg/95.0.1020.53"
    }
    res = requests.get(url, headers)
    name_data = res.json()
    return name_data["champion"]["biography"]["short"].strip("</p>")
